//
//  NewUserViewController.h
//  iWeighMyself
//	Abstract: controls the screen that allows the user to configure its preferences for the first time
//
//  Created by Francisco Gindre on 7/28/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "NewUserViewController.h"
#import "PeoplePickerDelegate.h"
#import "WeightUnitPickerViewController.h"
#import "EmailCellTextFieldDelegate.h"
#import "NameCellTextFieldDelegate.h"
#import "ContactSourceViewController.h"

@implementation NewUserViewController

@synthesize sectionList;
@synthesize cellDefaultValues;
@synthesize cellValues;
@synthesize nameCell;
@synthesize emailCell;
@synthesize appDelegate;
@synthesize defaultContactCellIndexPath;
@synthesize defaultContactDictionary;
@synthesize weightUnit;
@synthesize saveButton;
@synthesize isWeightUnitSet;
@synthesize weightUnitIndexPath;
@synthesize emailCellIndexPath;
@synthesize nameCellIndexPath;

#pragma mark -
#pragma mark constants

#define NAME_SECTION 0
#define NAME_CELL 0
#define EMAIL_SECTION 1
#define EMAIL_CELL 0

#define CONTACT_SECTION 2
#define CONTACT_CELL 0

#define UNIT_SECTION 3
#define UNIT_CELL 0



#pragma mark -
#pragma mark View lifecycle

/*
 Loads all the needed data from the user's settings plist file or if default settings if it doesn't exist.
 */

- (void)viewDidLoad {
    [super viewDidLoad];
	
	/*
	 create save button and show it
	 */
	
	saveButton =[[UIBarButtonItem alloc] initWithTitle:
												 NSLocalizedString(@"SaveButtonTitle",@"")
												 style:UIBarButtonItemStyleDone target:self action:@selector(applyNewValues:)];
	/*
	 show it in the navigation bar
	 */
	self.navigationItem.rightBarButtonItem =saveButton;
	
	
	
	
	/*
	 get application delegate
	 */
	
	self.appDelegate = (IWeighMyselfAppDelegate*)[[UIApplication sharedApplication]delegate];
	
	/*
	 load sections
	 */
	self.sectionList = [[NSMutableArray alloc]initWithObjects:NSLocalizedString(@"NameSectionTitle",@""),
				   NSLocalizedString(@"EmailSectionTitle",@""),
				   NSLocalizedString(@"DefaultRecipientSectionTitle",@""), 
				   NSLocalizedString(@"SelectWeightUnitSectionTitle",@""),nil];
	
	/*
	 if there is no previous bundle data, show default screen
	 */
	self.cellValues = [NSMutableArray array];

	if ([self.appDelegate isFirstTimeSetup]){
		
		/*
		 hide the back button, if its really needed to configure the app
		 */
		[self.navigationItem setHidesBackButton:YES];

		
		//init Name section cells
		[self.cellValues addObject:[NSMutableArray arrayWithObject:NSLocalizedString(@"NameDefaultValue",@"")]];
		
		//init Email section cells
		[self.cellValues addObject:[NSMutableArray arrayWithObject:NSLocalizedString(@"EmailDefaultValue",@"")]];
		
		// init Recipients section cells
		[self.cellValues addObject:[NSMutableArray arrayWithObject:NSLocalizedString(@"DefaultRecipientSectionTitle",@"")]];
		
		// init unit section cells
		[self.cellValues addObject:[NSMutableArray arrayWithObject:NSLocalizedString(@"SelectWeightUnitSectionTitle",@"")]];
		self.isWeightUnitSet = NO;
	} else {
		NSLog(@"property list loaded with values \n %@",appDelegate.plistXML);
		
		//init Name section cells
		[self.cellValues addObject:[NSMutableArray arrayWithObject:[self.appDelegate.plistXML objectForKey:@"Name"]]] ;
		
		// init Recipients section cells
		[self.cellValues addObject:[NSMutableArray arrayWithObject:[self.appDelegate.plistXML objectForKey:@"Email"]]];
		
		// init default contact section cells
		[self.cellValues addObject:[NSMutableArray arrayWithObject:[(NSMutableDictionary*)[self.appDelegate.plistXML objectForKey:@"DefaultContact"] objectForKey:@"DefaultContactName"]]];
		
		// init unit section cells
		[self.cellValues addObject:[NSMutableArray arrayWithObject:[self.appDelegate.plistXML objectForKey:@"WeightUnit"]]];
		self.isWeightUnitSet = YES;
		
			}
}



- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
	
	[self updateCellValues];
	NSLog(@"plist contains %@",self.appDelegate.plistXML);
	[self.tableView reloadData];
}

/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
	
	
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}
*/

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/


#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return [sectionList count];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
	return [(NSMutableArray*)[cellValues objectAtIndex:section]count];
	
	
}

// set section text 
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
	return [self.sectionList objectAtIndex:section];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	
		 
	// Show the corresponding cells
 
	switch (indexPath.section) {
		case NAME_SECTION:
			
			if (nameCellIndexPath==nil) {
				nameCellIndexPath=indexPath;
				[nameCellIndexPath retain];
			}
			/*
			 display a cell containing a texfield with an text keyboard
			 */
			
			return [self createEnterNameCellAtIndexPath:indexPath tableView:tableView];
			break;
		case EMAIL_SECTION:
			/* 
             check if the indexpath has been retained for later use
             */
            
            if (emailCellIndexPath==nil) {
				emailCellIndexPath=indexPath;
				[emailCellIndexPath retain];
				
			}
			/*
			 display a cell containing a textfield with an email keyboard
			 */
					return [self createEnterEmailCellAtIndexPath:indexPath tableview:tableView];
			break;
			
		case CONTACT_SECTION:
            if (self.defaultContactCellIndexPath==nil){
                
                self.defaultContactCellIndexPath = indexPath;
                [self.defaultContactCellIndexPath retain];
                
            }
			return [self createPlainCellWithDisclosureAccessoryAtIndexPath:indexPath tableView:tableView];			
			break;

		case UNIT_SECTION:
			if (self.weightUnitIndexPath==nil) {
				self.weightUnitIndexPath= indexPath;
				[self.weightUnitIndexPath retain];
			}
            return [self createPlainCellWithDisclosureAccessoryAtIndexPath:indexPath tableView:tableView];			
			break;
        }
	
	return nil; //shouldn't get here
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark -
#pragma mark Custom cell creation methods

/*
 returns a cell containing an UITextField configured as keyboard for text (not email)
 */
- (UITableViewCell *) createEnterNameCellAtIndexPath :(NSIndexPath*)indexPath tableView:(UITableView *) tableView  {
	
	static NSString *cellIdentifier = @"KeyBoardTextFieldCell";
    
    KeyBoardTextFieldCell *cell = (KeyBoardTextFieldCell*)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
	if (cell == nil) {
		// get cell from the bundle
		[[NSBundle mainBundle] loadNibNamed:@"KeyBoardTextFieldCellNib" owner:self options:nil];
		
		//pass the references to cell
		cell = nameCell;
		//self.nameCell = nil;
	    
    }
	/*
	 turn blue selection off
	 */
	
	cell.selectionStyle = UITableViewCellSelectionStyleNone;
	
	/*
	 set the delegate of the name text field
	 */
	
	cell.nameTextField.delegate = [[NameCellTextFieldDelegate alloc]initWithNewUserViewController:self];
	
	//set the content of the UITextField inside the cell 
	
	[cell.nameTextField setText:[(NSMutableArray*)[self.cellValues objectAtIndex:indexPath.section] objectAtIndex:indexPath.row]];
	NSLog(@"name cell has value %@",[(NSMutableArray*)[cellValues objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] );
	
	return cell;
		
}

/*
 Creates a cell containing a textfield configured with email keyboard
 */

- (UITableViewCell*)createEnterEmailCellAtIndexPath:(NSIndexPath*)indexPath tableview:(UITableView*)tableView {
	static NSString *cellIdentifier = @"KeyBoardEmailTextFieldCell";
    
    KeyBoardTextFieldCell *cell = (KeyBoardTextFieldCell*)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
	if (cell == nil) {
		// get cell from the bundle
		[[NSBundle mainBundle] loadNibNamed:@"KeyBoardTextFieldCellNib" owner:self options:nil];
		
		//pass the references to cell
		cell = nameCell;
		//self.nameCell = nil;
	    
    }
	/*
	 turn off blue selection
	 */
	
	cell.selectionStyle = UITableViewCellSelectionStyleNone;
	/*
	 set the email keyboard 
	 */
	
	cell.nameTextField.keyboardType = UIKeyboardTypeEmailAddress;
	[cell.nameTextField setText:[(NSMutableArray*)[cellValues objectAtIndex:indexPath.section] objectAtIndex:indexPath.row]];
    NSLog(@"cell has value %@",[(NSMutableArray*)[cellValues objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] );
    
	/*
	 set the email textfield delegate
	 */
	cell.nameTextField.delegate = [[EmailCellTextFieldDelegate alloc] initWithNewUserViewController:self];
	
	return cell;

}

/*
 Create plain standard cell with detailed accessory
 */
-(UITableViewCell*) createPlainCellWithDisclosureAccessoryAtIndexPath:(NSIndexPath*)indexPath tableView:(UITableView*)tableView{	
	UITableViewCell *cell;
	NSString *cellIdentifier = @"Cell";
	
	cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
	
	//if cell hasn't been reused alloc and init one 
	
	if (cell == nil) {
		
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier] autorelease];
	
		
	}	
	cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
	
	// set the text for this cell 
	NSString *textToSet =(NSString*) [(NSMutableArray*)[self.cellValues objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
		
	[cell.textLabel setText:textToSet];
	
	return cell;
}
	

#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
   
	ContactSourceViewController *contactSelectionScreen =[[ContactSourceViewController alloc]initWithNibName:@"ContactSourceViewController" bundle:[NSBundle mainBundle]];
	
	
	switch (indexPath.section) {
			
		case NAME_SECTION:
			/*
			 text field covers up the whole cell, so nothing to be done here
			 */
			break;
		case EMAIL_SECTION:
			/*
			 text field covers up the whole cell, so nothing to be done here
			 */
			break;

		case CONTACT_SECTION:
			
			
			/*
			 show the contact selection screen
			 */
			[self.navigationController pushViewController:contactSelectionScreen animated:YES];
			

			
			
			break;
		
		case UNIT_SECTION:
			/*
			 show the weight unit picker 
			 */
			
			[self showWeightUnitPicker];				
			break;
	}
	
}




#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}

#pragma mark -
#pragma mark Keyboard handling
/*
 makes the keyboard retreat
 */
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
	[textField resignFirstResponder];
	return YES;
}

#pragma mark -
#pragma mark Custom Methods



/*
 saves the changed values. Why not put this on the app delegate? because all the needed information belongs to 
 this screen.
 
 */

-(void) applyNewValues:(id)sender {
	
	/*
	 if it's the first time the app being run, there can be values that were not configured
	 before pressing the "save" button. In that case alerts will arise asking the user to 
	 fulfill those values
	 
	 NOTE: due to application workflow it's not possible (in normal usage circumstances)
	 to run the application with no UserData.plist file
	 */
	
	
		
	/*
	 check if the default contact has been chosen in order to save settings
	 otherwise raise alert
	 */
	
	if ([self.appDelegate.plistXML objectForKey:@"DefaultContact"]==nil) {
		
		UIAlertView *alert= [[UIAlertView alloc]initWithTitle:NSLocalizedString(@"InfoMissingAlertTitle",@"") 
													  message:NSLocalizedString(@"InfoMissingAlertMessage",@"") delegate:nil 
											cancelButtonTitle:NSLocalizedString(@"AlertCloseButtonTitle",@"") 
											otherButtonTitles:nil];
		[alert show];
		[alert release];
		
		
	} else {
		/*
		 if there's no weight unit selected raise alert
		 */
		if(!self.isWeightUnitSet){
			UIAlertView *weightAlert= [[UIAlertView alloc]initWithTitle:NSLocalizedString(@"InfoMissingAlertTitle",@"") 
														  message:NSLocalizedString(@"WeightUnitInfoMissingAlertMessage",@"") delegate:nil 
												cancelButtonTitle:NSLocalizedString(@"AlertCloseButtonTitle",@"") 
												otherButtonTitles:nil];
			[weightAlert show];
			[weightAlert release];
		
		} else {

			nameCell = (KeyBoardTextFieldCell*)[self.tableView cellForRowAtIndexPath:nameCellIndexPath];
			emailCell = (KeyBoardTextFieldCell*)[self.tableView cellForRowAtIndexPath:emailCellIndexPath];		
			
			/*
			 put the NSMutableDictionary containing the DefaultContact in plistXML. 
			*/
			
			//NSLog(@"ns dictionary has %@",self.appDelegate.plistXML);
			
			//[appDelegate.plistXML setObject:defaultContactDictionary forKey:@"DefaultContact"];

			/*
			 put the name on the dictionary
			 */

			[self.appDelegate.plistXML setObject:nameCell.nameTextField.text forKey:@"Name"];
			
			// NSLog(@"name on namecell %@", nameCell.nameTextField.text);
			// NSLog(@"name on cellValues: %@",[cellValues objectAtIndex:NAME_SECTION]);
			 
			/*
			 put the email on the dictionary
			 */
			[self.appDelegate.plistXML setObject:emailCell.nameTextField.text forKey:@"Email"];

			/*
			 put the weight unit on the dictionary
			 */

			weightUnit =(NSString*) [(NSMutableArray*)[cellValues objectAtIndex:UNIT_SECTION]objectAtIndex:UNIT_CELL];


			[self.appDelegate.plistXML setObject:weightUnit forKey:@"WeightUnit"];
			
			
		//	NSLog(@"resultant plistXML before saving: %@",self.appDelegate.plistXML);
			NSError *error = [[NSError alloc]init];

			NSData *plistData =[NSPropertyListSerialization dataWithPropertyList:appDelegate.plistXML format:NSPropertyListXMLFormat_v1_0 options:0 error:&error];

			if (plistData) {
				[plistData writeToFile:self.appDelegate.plistPath atomically:YES];
				/*
				 Now that configuration is done, show the back button again
				 */
				[self.navigationItem setHidesBackButton:NO];
			}
			else {
				/*
				 pop up alert if error ocurred
				 */
				NSLog(@"error: %@", error);
				UIAlertView *alert= [[UIAlertView alloc]initWithTitle:NSLocalizedString(@"WriteSettingsErrorTitle",@"") 
															  message:NSLocalizedString(@"WriteSettingsErrorMessage",@"") delegate:nil 
													cancelButtonTitle:NSLocalizedString(@"AlertCloseButtonTitle",@"") 
													otherButtonTitles:nil];
				[alert show];
				[alert release];
			}
		}
	}
}
			


/* 
 loads values that might have changed on other views e.g.: choose default recipient
 */

-(void) updateCellValues {
   
    
    
	
    //get the default contact name from the contact if there is any
    if(self.appDelegate.plistXML !=nil &&[self.appDelegate.plistXML count]!=0){
		self.defaultContactDictionary = [self.appDelegate.plistXML objectForKey:@"DefaultContact"];    
		
		//NSLog(@"plistxml has %@",appDelegate.plistXML);
		
		//NSLog(@"defaultContactItem has %@", self.defaultContactDictionary);
		//update what the interface will pick up from cellValues
		
		if (self.defaultContactDictionary!=nil)
			[(NSMutableArray*)[cellValues objectAtIndex:CONTACT_SECTION]replaceObjectAtIndex:CONTACT_CELL withObject:[self.defaultContactDictionary objectForKey:@"DefaultContactName"]];
	 
		//[defaultContactItem release];
	 
    }
	
//	NSLog(@"cell values contains: %@",cellValues);
	
	
}


/*
 shows the weight unit picker
 */

-(void)showWeightUnitPicker {
	WeightUnitPickerViewController * weightPickerView = [[WeightUnitPickerViewController alloc]initWithParentView:self];
	
	[appDelegate.navigationController pushViewController:weightPickerView animated:YES];
	
}

@end

